#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import tkinter as tk
from tkinter import ttk, messagebox, simpledialog

class CharacterWindow:
    def __init__(self, parent, game_manager):
        self.parent = parent
        self.game_manager = game_manager
        self.window = tk.Toplevel(parent)
        self.setup_window()
        self.create_widgets()
        self.refresh_character_list()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title("角色管理")
        self.window.geometry("600x500")
        self.window.resizable(True, True)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 50, self.parent.winfo_rooty() + 50))
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.window.columnconfigure(0, weight=1)
        self.window.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(1, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="角色管理", font=('Arial', 14, 'bold'))
        title_label.grid(row=0, column=0, pady=(0, 10))
        
        # 角色列表框架
        list_frame = ttk.LabelFrame(main_frame, text="角色列表", padding="10")
        list_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        list_frame.columnconfigure(0, weight=1)
        list_frame.rowconfigure(0, weight=1)
        
        # 创建Treeview显示角色列表
        columns = ('name', 'class', 'level', 'exp', 'status', 'char_id')
        self.char_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=10)
        
        # 隐藏char_id列（用于存储角色ID）
        self.char_tree.column('char_id', width=0, stretch=False)
        self.char_tree.heading('char_id', text='')
        
        # 设置列标题
        self.char_tree.heading('name', text='角色名')
        self.char_tree.heading('class', text='职业')
        self.char_tree.heading('level', text='等级')
        self.char_tree.heading('exp', text='经验')
        self.char_tree.heading('status', text='状态')
        
        # 设置列宽
        self.char_tree.column('name', width=120)
        self.char_tree.column('class', width=80)
        self.char_tree.column('level', width=60)
        self.char_tree.column('exp', width=100)
        self.char_tree.column('status', width=120)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.char_tree.yview)
        self.char_tree.configure(yscrollcommand=scrollbar.set)
        
        self.char_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 绑定双击事件
        self.char_tree.bind('<Double-1>', self.on_character_double_click)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 按钮
        ttk.Button(button_frame, text="创建角色", command=self.create_character).grid(row=0, column=0, padx=(0, 5))
        ttk.Button(button_frame, text="选择角色", command=self.select_character).grid(row=0, column=1, padx=5)
        ttk.Button(button_frame, text="删除角色", command=self.delete_character).grid(row=0, column=2, padx=5)
        ttk.Button(button_frame, text="角色详情", command=self.show_character_details).grid(row=0, column=3, padx=5)
        
        # 关闭按钮
        ttk.Button(main_frame, text="关闭", command=self.close_window).grid(row=3, column=0, pady=(10, 0))
        
    def refresh_character_list(self):
        """刷新角色列表"""
        # 清空现有项目
        for item in self.char_tree.get_children():
            self.char_tree.delete(item)
            
        # 获取所有角色
        characters = self.game_manager.get_all_characters()
        current_char = self.game_manager.get_current_character()
        current_char_id = current_char.id if current_char else None
        
        for char in characters:
            # 确定状态
            if char.is_idle:
                status = f"挂机中 ({char.idle_location})"
            elif char.is_in_battle:
                status = "战斗中"
            else:
                status = "空闲"
                
            # 如果是当前角色，在名字前加标记
            name = f"★ {char.name}" if char.id == current_char_id else char.name
            
            # 插入数据（包含角色ID）
            item = self.char_tree.insert('', 'end', values=(
                name,
                char.character_class,
                char.level,
                f"{char.exp}/{char.exp_to_next_level}",
                status,
                char.id  # 角色ID存储在隐藏列中
            ))
            
    def get_selected_character_id(self):
        """获取选中的角色ID"""
        selection = self.char_tree.selection()
        if not selection:
            return None
        item = selection[0]
        values = self.char_tree.item(item, 'values')
        return values[5] if len(values) > 5 else None  # char_id在第6列（索引5）
        
    def create_character(self):
        """创建新角色"""
        dialog = CharacterCreateDialog(self.window, self.game_manager)
        if dialog.result:
            self.refresh_character_list()
            
    def select_character(self):
        """选择角色"""
        char_id = self.get_selected_character_id()
        if not char_id:
            messagebox.showwarning("警告", "请先选择一个角色！")
            return
            
        try:
            self.game_manager.select_character(char_id)
            messagebox.showinfo("成功", "角色已选择！")
            self.refresh_character_list()
        except Exception as e:
            messagebox.showerror("错误", f"选择角色失败: {str(e)}")
            
    def delete_character(self):
        """删除角色"""
        char_id = self.get_selected_character_id()
        if not char_id:
            messagebox.showwarning("警告", "请先选择一个角色！")
            return
            
        # 获取角色信息
        char = None
        for c in self.game_manager.get_all_characters():
            if c.id == char_id:
                char = c
                break
                
        if not char:
            messagebox.showerror("错误", "角色不存在！")
            return
            
        # 确认删除
        if messagebox.askyesno("确认删除", f"确定要删除角色 '{char.name}' 吗？\n此操作不可撤销！"):
            try:
                success, message = self.game_manager.character_manager.delete_character(char_id)
                if success:
                    messagebox.showinfo("成功", "角色已删除！")
                    self.refresh_character_list()
                else:
                    messagebox.showerror("错误", message)
            except Exception as e:
                messagebox.showerror("错误", f"删除角色失败: {str(e)}")
                
    def show_character_details(self):
        """显示角色详情"""
        char_id = self.get_selected_character_id()
        if not char_id:
            messagebox.showwarning("警告", "请先选择一个角色！")
            return
            
        # 获取角色信息
        char = None
        for c in self.game_manager.get_all_characters():
            if c.id == char_id:
                char = c
                break
                
        if not char:
            messagebox.showerror("错误", "角色不存在！")
            return
            
        CharacterDetailDialog(self.window, char)
        
    def on_character_double_click(self, event):
        """双击角色时选择该角色"""
        self.select_character()
        
    def close_window(self):
        """关闭窗口"""
        self.window.destroy()

class CharacterCreateDialog:
    def __init__(self, parent, game_manager):
        self.parent = parent
        self.game_manager = game_manager
        self.result = None
        self.window = tk.Toplevel(parent)
        self.setup_window()
        self.create_widgets()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title("创建角色")
        self.window.geometry("400x300")
        self.window.resizable(False, False)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 100, self.parent.winfo_rooty() + 100))
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        ttk.Label(main_frame, text="创建新角色", font=('Arial', 14, 'bold')).grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 角色名输入
        ttk.Label(main_frame, text="角色名:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.name_entry = ttk.Entry(main_frame, width=20)
        self.name_entry.grid(row=1, column=1, sticky=(tk.W, tk.E), pady=5)
        
        # 职业选择
        ttk.Label(main_frame, text="职业:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.class_var = tk.StringVar()
        class_combo = ttk.Combobox(main_frame, textvariable=self.class_var, state="readonly", width=18)
        class_combo['values'] = self.game_manager.character_manager.get_character_classes()
        class_combo.grid(row=2, column=1, sticky=(tk.W, tk.E), pady=5)
        class_combo.current(0)  # 默认选择第一个
        
        # 职业描述
        desc_frame = ttk.LabelFrame(main_frame, text="职业描述", padding="10")
        desc_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(10, 0))
        
        self.desc_text = tk.Text(desc_frame, height=6, width=40, wrap=tk.WORD, state=tk.DISABLED)
        self.desc_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 绑定职业选择事件
        class_combo.bind('<<ComboboxSelected>>', self.on_class_selected)
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=4, column=0, columnspan=2, pady=(20, 0))
        
        ttk.Button(button_frame, text="创建", command=self.create_character).grid(row=0, column=0, padx=(0, 10))
        ttk.Button(button_frame, text="取消", command=self.cancel).grid(row=0, column=1)
        
        # 配置网格权重
        main_frame.columnconfigure(1, weight=1)
        desc_frame.columnconfigure(0, weight=1)
        desc_frame.rowconfigure(0, weight=1)
        
        # 初始显示第一个职业的描述
        self.on_class_selected(None)
        
    def on_class_selected(self, event):
        """职业选择改变时更新描述"""
        class_descriptions = {
            "战士": "近战物理职业，拥有高生命值和防御力，\n适合承受伤害和保护队友。\n\n属性加成：\n• 生命值 +20\n• 防御力 +10\n• 攻击力 +5",
            "法师": "远程魔法职业，拥有高魔法值和攻击力，\n能够造成大量魔法伤害。\n\n属性加成：\n• 魔法值 +20\n• 攻击力 +10\n• 速度 +5",
            "弓箭手": "远程物理职业，拥有高速度和攻击力，\n擅长快速攻击和风筝战术。\n\n属性加成：\n• 速度 +15\n• 攻击力 +8\n• 生命值 +5",
            "刺客": "敏捷型职业，拥有极高的速度和爆发力，\n擅长快速击杀敌人。\n\n属性加成：\n• 速度 +20\n• 攻击力 +12\n• 生命值 -5",
            "牧师": "辅助型职业，拥有高魔法值和治疗能力，\n能够为队友提供支援和治疗。\n\n属性加成：\n• 魔法值 +25\n• 防御力 +8\n• 生命值 +10"
        }
        
        selected_class = self.class_var.get()
        description = class_descriptions.get(selected_class, "")
        
        self.desc_text.config(state=tk.NORMAL)
        self.desc_text.delete(1.0, tk.END)
        self.desc_text.insert(1.0, description)
        self.desc_text.config(state=tk.DISABLED)
        
    def create_character(self):
        """创建角色"""
        name = self.name_entry.get().strip()
        char_class = self.class_var.get()
        
        if not name:
            messagebox.showwarning("警告", "请输入角色名！")
            return
            
        if not char_class:
            messagebox.showwarning("警告", "请选择职业！")
            return
            
        try:
            success, message, character = self.game_manager.create_character(name, char_class)
            if success:
                self.result = character
                messagebox.showinfo("成功", f"角色 '{name}' 创建成功！")
                self.window.destroy()
            else:
                messagebox.showerror("错误", message)
        except Exception as e:
            messagebox.showerror("错误", f"创建角色失败: {str(e)}")
            
    def cancel(self):
        """取消创建"""
        self.window.destroy()

class CharacterDetailDialog:
    def __init__(self, parent, character):
        self.parent = parent
        self.character = character
        self.window = tk.Toplevel(parent)
        self.setup_window()
        self.create_widgets()
        
    def setup_window(self):
        """设置窗口"""
        self.window.title(f"角色详情 - {self.character.name}")
        self.window.geometry("400x500")
        self.window.resizable(False, False)
        self.window.configure(bg='#f0f0f0')
        
        # 设置为模态窗口
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # 居中显示
        self.window.geometry("+%d+%d" % (self.parent.winfo_rootx() + 100, self.parent.winfo_rooty() + 50))
        
    def create_widgets(self):
        """创建界面组件"""
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 标题
        ttk.Label(main_frame, text=f"角色详情", font=('Arial', 14, 'bold')).grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        # 基本信息
        info_frame = ttk.LabelFrame(main_frame, text="基本信息", padding="10")
        info_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        ttk.Label(info_frame, text="角色名:").grid(row=0, column=0, sticky=tk.W, pady=2)
        ttk.Label(info_frame, text=self.character.name, font=('Arial', 10, 'bold')).grid(row=0, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(info_frame, text="职业:").grid(row=1, column=0, sticky=tk.W, pady=2)
        ttk.Label(info_frame, text=self.character.character_class).grid(row=1, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(info_frame, text="等级:").grid(row=2, column=0, sticky=tk.W, pady=2)
        ttk.Label(info_frame, text=str(self.character.level)).grid(row=2, column=1, sticky=tk.W, pady=2)
        
        # 属性信息
        attr_frame = ttk.LabelFrame(main_frame, text="属性信息", padding="10")
        attr_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        ttk.Label(attr_frame, text="生命值:").grid(row=0, column=0, sticky=tk.W, pady=2)
        ttk.Label(attr_frame, text=f"{self.character.hp}/{self.character.max_hp}").grid(row=0, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(attr_frame, text="魔法值:").grid(row=1, column=0, sticky=tk.W, pady=2)
        ttk.Label(attr_frame, text=f"{self.character.mp}/{self.character.max_mp}").grid(row=1, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(attr_frame, text="攻击力:").grid(row=2, column=0, sticky=tk.W, pady=2)
        ttk.Label(attr_frame, text=str(self.character.attack)).grid(row=2, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(attr_frame, text="防御力:").grid(row=3, column=0, sticky=tk.W, pady=2)
        ttk.Label(attr_frame, text=str(self.character.defense)).grid(row=3, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(attr_frame, text="速度:").grid(row=4, column=0, sticky=tk.W, pady=2)
        ttk.Label(attr_frame, text=str(self.character.speed)).grid(row=4, column=1, sticky=tk.W, pady=2)
        
        # 经验信息
        exp_frame = ttk.LabelFrame(main_frame, text="经验信息", padding="10")
        exp_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        ttk.Label(exp_frame, text="当前经验:").grid(row=0, column=0, sticky=tk.W, pady=2)
        ttk.Label(exp_frame, text=str(self.character.exp)).grid(row=0, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(exp_frame, text="升级所需:").grid(row=1, column=0, sticky=tk.W, pady=2)
        ttk.Label(exp_frame, text=str(self.character.exp_to_next_level)).grid(row=1, column=1, sticky=tk.W, pady=2)
        
        ttk.Label(exp_frame, text="进度:").grid(row=2, column=0, sticky=tk.W, pady=2)
        progress = (self.character.exp / self.character.exp_to_next_level) * 100
        ttk.Label(exp_frame, text=f"{progress:.1f}%").grid(row=2, column=1, sticky=tk.W, pady=2)
        
        # 状态信息
        status_frame = ttk.LabelFrame(main_frame, text="当前状态", padding="10")
        status_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        if self.character.is_idle:
            status_text = f"挂机中\n地点: {self.character.idle_location}"
        elif self.character.is_in_battle:
            status_text = f"战斗中\n战斗ID: {self.character.battle_id}"
        else:
            status_text = "空闲"
            
        ttk.Label(status_frame, text=status_text).grid(row=0, column=0, sticky=tk.W)
        
        # 关闭按钮
        ttk.Button(main_frame, text="关闭", command=self.window.destroy).grid(row=5, column=0, columnspan=2, pady=(20, 0))
        
        # 配置网格权重
        main_frame.columnconfigure(1, weight=1)
        info_frame.columnconfigure(1, weight=1)
        attr_frame.columnconfigure(1, weight=1)
        exp_frame.columnconfigure(1, weight=1)
        status_frame.columnconfigure(0, weight=1)